package com.sljy.hzk.util;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//监听类
public class EventListenerManager {
    private static EventListenerManager listener = null;
    private  Map<String, List<EventBase>> eventMap = new HashMap<String, List<EventBase>>();
    public static EventListenerManager Instance(){
        if(listener==null)listener = new EventListenerManager();
        return listener;
    }
    /**
     //添加事件
    */
    public void addEventLisener(Object eventActive, String methodName,Object...args){
        EventBase e = new EventBase(eventActive,methodName,args);
        if(!eventMap.containsKey(methodName)){
            List<EventBase> l = new ArrayList<EventBase>();
            l.add(e);
            eventMap.put(methodName, l);
        }else
            eventMap.get(methodName).add(e);
    }
    /**
     //移除事件
     */
   // @RequiresApi(api = Build.VERSION_CODES.N)
    public void removeEventLisener(Object eventActive, String methodName) {
        if(eventMap.containsKey(methodName)){
             boolean remove = eventMap.get(methodName).remove(eventActive);
            Log.i("移除事件",remove?"正常":"异常");
        }
    }
    /**
     //移除同名称的所有事件
     */
    public void removeEventLisener(String methodName) {
        if(eventMap.containsKey(methodName)){
            List<EventBase> remove = eventMap.remove(methodName);
            Log.i("移除该名称的所有事件","成功");
        }
    }

    /**
     //发送消息
     */
    public void sendEvent(String methodName, Object...args) throws Exception {
        if(eventMap.containsKey(methodName)){
            List<EventBase> list = eventMap.get(methodName);
            for(EventBase e : list){
                e.invoke(args);
            }
        }
    }
}